package com.xiaoma.h5testdemo.collect

import com.xiaoma.common.utils.AppHolder
import com.xiaoma.h5testdemo.common.models.CollectEntity
import com.xiaoma.lib.log.KLog
import com.xiaoma.lib.store.TPUtils
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/**
 * author: liangjingbo
 * date: 2024/4/18
 * describe:
 */
object CollectMgr {

    private val mCollectList = arrayListOf<CollectEntity>()
    private val mutex = Mutex()
    private const val KEY_SAVE_COLLECT_LIST = "KEY_SAVE_COLLECT_LIST"
    private var hasInited = false
    private val TAG = CollectMgr::class.java.simpleName + "_XMTag"

    suspend fun isCollected(entity: CollectEntity): Boolean {
        mutex.withLock {
            if (entity.url.isNullOrEmpty()) {
                return false
            }
            readCollectListFromLocal()
            val result = mCollectList.find { it.url.contentEquals(entity.url, true) }
            return result != null
        }
    }

    suspend fun getCollectList(): List<CollectEntity> {
        mutex.withLock {
            readCollectListFromLocal()
            return mCollectList
        }
    }

    private fun saveCollectListToLocal() {
        TPUtils.putList(AppHolder.app, KEY_SAVE_COLLECT_LIST, mCollectList)
        KLog.i(TAG, "saveCollectListToLocal() ")
    }

    private fun readCollectListFromLocal() {
        if (hasInited) return
        KLog.i(TAG, "readCollectListFromLocal() ")
        hasInited = true
        val list = TPUtils.getList(AppHolder.app, KEY_SAVE_COLLECT_LIST, Array<CollectEntity>::class.java)
        if (!list.isNullOrEmpty()) {
            mCollectList.addAll(list)
        }
    }

    suspend fun handleCollect(entity: CollectEntity, block: (Boolean) -> Unit) {
        mutex.withLock {
            if (entity.url.isNullOrEmpty()) return
            readCollectListFromLocal()
            val result = mCollectList.find { it.url.contentEquals(entity.url, true) }
            var collect = false
            if (result == null) {
                mCollectList.add(entity)
                collect = true
            } else {
                removeTargetEntity(entity)
            }
            saveCollectListToLocal()
            block.invoke(collect)
        }

    }

    private fun removeTargetEntity(target: CollectEntity) {
        val iterator = mCollectList.iterator()
        while (iterator.hasNext()){
            val entity = iterator.next()
            if (entity.url.contentEquals(target.url,true)){
                iterator.remove()
                break
            }
        }
    }
}